package com.rong.juc_test.juc_p6_p7;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 线程等待和唤醒的方法
 */
public class AwakeThreadDemo {
    /**
     * 1. 使用Object中的wait()方法让线程等待，Object中的nofity()唤醒线程
     * ● 必须在同步代码块中使用，需要先持有锁，否则报错
     * ● notify必须放在wait之后，否则程序无法执行，无法唤醒
     */
    private static void t1() {
        Object obj = new Object();
        new Thread(() -> {
            synchronized(obj){
                System.out.println(Thread.currentThread().getName() + "comein");
                try {
                    System.out.println(Thread.currentThread().getName() + "等待");
                    obj.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "被唤醒");
            }
        },"t1").start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(() -> {
            synchronized(obj){
                System.out.println(Thread.currentThread().getName() + "comein 唤醒t1");
                obj.notify();
            }
        },"t2").start();
    }

    /**
     * 2. JUC中的await()让线程等待，signal()唤醒线程
     * ● 必须在lock unlock锁块中使用
     * ● 先await后singal
     */
    private static void t2() {
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        new Thread(() -> {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "comein 等待");
                try {
                    condition.await();
                    System.out.println(Thread.currentThread().getName() + "被唤醒");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }finally {
                lock.unlock();
            }
        },"t1").start();

        new Thread(() -> {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "comein 发出唤醒通知");
                condition.signal();
            }finally {
                lock.unlock();
            }
        },"t2").start();
    }

    public static void main(String[] args) {
    }




}
